import { validateGroupWindow } from "../validateGroup";
import { ModelValidateDegree, ModelData, modelService, projectService, CanLoadMethods, modelTreeMultiSelectWindow, ipcWindowUtil, CheckElementsByRulesDto, ValidateConfigDto, ValidateRuleItemResponse, rmi } from "@/mdesign-lib/mdesign-app.umd.js";

type ValidateGroupItem = {
  icon: string;
  label: string;
  value: string;
  key: string;
  children?: ValidateGroupItem[];
};

export class ValidateRuleModel {
  saveLoading = false;

  modelRange: ModelData[] = [];
  rules: ValidateRuleItemResponse[] = [];
  severity?: ModelValidateDegree;
  excludeReadOnly = true;
  validationLoading = false;
  instancesIds: string[] = [];
  validateGroupTreeData: ValidateGroupItem[] = [];
  selectedKeys: string[] = [];

  constructor(public projectId: string, public modelId: string) {}

  async initial() {
    await this.loadData();
    await this.getValidateGroup();
  }

  async loadData() {
    this.severity = ModelValidateDegree.ERROR;
    const rootNodeId = (await rmi.invoke("app.activeProject.nodePool.getRootNodeId", [])) as string;
    const instanceIds = this.modelId ? [this.modelId] : [rootNodeId];
    this.setModelRange(instanceIds);
  }

  async updateData(dto: Partial<ValidateConfigDto>) {
    await projectService.saveValidateConfig({ projectId: this.projectId, ...dto });
  }

  async setModelRange(ids: string[]) {
    if (!ids || ids.length === 0) {
      this.modelRange = [];
    } else {
      const modelRange = await modelService.getModelDatas(this.projectId, ids);
      this.modelRange = modelRange;
    }
  }

  async choiceModelRange() {
    const res = await modelTreeMultiSelectWindow.popup({
      attrTip: "checkbox",
      title: "选择校验范围",
      loadMethod: CanLoadMethods.getPropertyTreeList,
      loadParams: JSON.stringify({
        row: {
          checkMethod: "skipCheck",
          instanceId: "",
          key: "",
          moreBtnCondition: ""
        },
        projectId: this.projectId
      }),
      multiple: true,
      isUserCreation: true,
      rightSelectedIds: this.modelRange.map(item => item.id),
      delay: false,
      showNodeLabel: true
    });
    if (!res.success || !res.selectedId) return;
    await this.setModelRange(res.selectedId as string[]);
    await this.updateData({ instanceIds: res.selectedId as string[] });
  }

  async triggerCheck() {
    if (!this.selectedKeys.length) {
      return app.$notify({ type: "warning", title: "提醒", message: "请选择校验分组" });
    }
    this.instancesIds = [];
    const groupParams = {
      projectId: this.projectId,
      validationGroupInstanceIds: this.selectedKeys,
      severity: this.severity!
    };
    this.instancesIds = await modelService.queryValidationRuleInstanceIds(groupParams);
    this.validationLoading = true;
    const params = {
      projectId: this.projectId,
      ruleInstanceIds: this.instancesIds,
      excludeReadOnly: this.excludeReadOnly,
      instanceIds: this.modelRange.map(it => it.id),
      isCheckChildren: true,
      severity: this.severity
    } as CheckElementsByRulesDto;
    this.validationLoading = false;
    ipcWindowUtil.sendWindowChange({ success: true, checkStart: true, params: [JSON.parse(JSON.stringify(params))] });
    ipcWindowUtil.closeWindow();
  }

  close() {
    ipcWindowUtil.closeWindow({ success: false });
  }
  async getValidateGroup() {
    const response: { instanceId: string; instanceName: string; icon: string }[] = await modelService.queryValidationGroups(this.projectId);
    const options = response.map(item => ({
      ...item,
      icon: modelService.getModelIcon(this.projectId, item.icon),
      label: item.instanceName,
      value: item.instanceId,
      key: item.instanceId
    }));
    this.validateGroupTreeData = [
      {
        label: "全部分组",
        value: "all",
        key: "all",
        icon: "statics/images/sysml/Package.svg",
        children: options
      }
    ];
    this.selectedKeys = options.map(item => item.instanceId);
  }

  async openValidateGroupWindow() {
    validateGroupWindow.popup({ projectId: this.projectId, isEdit: false }, async res => {
      if (res.success) {
        validateGroupWindow.done();
      }
    });
  }
}
